<template>
  <el-dialog v-model="mapVisible" title="选择位置" width="55%" :before-close="handleClose" :modal="false" draggable>
    <div class="main">
      <div id="map"></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="btn-cancel" @click="dialogCancel">取消</el-button>
        <el-button class="btn-confirm" type="primary" @click="dialogConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref, onMounted, defineProps, defineEmits} from 'vue';

const mapVisible = ref(true);
let map: any; // 地图实例
let lnglat: any;
const props = defineProps({
  mapVisible: Boolean,
});

const initMap = () => {
  map = new AMap.Map('map', {
    resizeEnable: true, // 是否监控地图容器尺寸变化
    zoom: 11, // 初始化地图层级
  });
  let marker;
  let address;
  map.on('click', (e) => {
    lnglat = [Number(e.lnglat.lng), Number(e.lnglat.lat)];
    if (marker) {
      marker.setMap(null);
      marker = null;
    }
    marker = new AMap.Marker({
      position: lnglat,
      offset: new AMap.Pixel(-16, -16),
      zIndex: 100,
    });
    const geocoder = new AMap.Geocoder({});

    geocoder.getAddress(lnglat, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        address = result.regeocode.formattedAddress;
        marker.setLabel({
          offset: new AMap.Pixel(2, -70), // 设置文本标注偏移量
          content: `<div class='info'>
      <p>登记位置</p>
      <div class='line'></div>
      <div class='text'>${address}</div>
      <div class='lng'>经度：<span>${lnglat[0]}</span></div>
      <div classs='lat'>经度：<span>${lnglat[1]}</span></div>
      </div>`,
          direction: 'right',
        });
        map.add(marker);
      }
    });
  });
};

const dialogCancel = () => {
  mapVisible.value = !mapVisible.value;
};
const dialogConfirm = () => {
  emit('updateLocation', lnglat);
  mapVisible.value = !mapVisible.value;
};

const emit = defineEmits(['closeDialog', 'updateLocation']);

const handleClose = () => {
  emit('closeDialog');
};
onMounted(() => {
  setTimeout(() => {
    initMap();
  }, 10);
});
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
}
#map {
  height: 50vh;
  &:deep(.amap-marker-label) {
    border: 0;
    min-width: 280px;
    min-height: 110px;
    .info {
      padding: 10px;
      > p {
        margin: 0;
      }
      .line {
        height: 1px;
        margin-top: 5px;
        background: rgba(0, 0, 0, 0.06);
      }
      .text {
        margin: 5px 0;
        overflow: hidden;
      }
      .lng,
      .lat {
        margin: 5px 0;
      }
    }
  }
}
</style>
